<template>
  <div class="demo">
    <div class="demo-title">动态增减嵌套字段</div>
    <div class="demo-content">
      <Form
        ref="formRef"
        name="dynamic_form_nest_item"
        :model="dynamicValidateForm"
        @finish="onFinish"
      >
        <Space
          v-for="(user, index) in dynamicValidateForm.users"
          :key="user.id"
          style="display: flex; margin-bottom: 8px"
          align="baseline"
        >
          <Form.Item
            :name="['users', index, 'first']"
            :rules="{ required: true, message: 'Missing first name' }"
          >
            <Input v-model:value="user.first" placeholder="First Name" />
          </Form.Item>
          <Form.Item
            :name="['users', index, 'last']"
            :rules="{
              required: true,
              message: 'Missing last name',
            }"
          >
            <Input v-model:value="user.last" placeholder="Last Name" />
          </Form.Item>
          <MinusCircleOutlined @click="removeUser(user)" />
        </Space>
        <Form.Item>
          <Button type="dashed" block @click="addUser">
            <PlusOutlined />
            Add user
          </Button>
        </Form.Item>
        <Form.Item>
          <Button type="primary" html-type="submit">Submit</Button>
        </Form.Item>
      </Form>
    </div>
  </div>
</template>

<script lang="ts" setup>
  import { reactive, ref } from 'vue';
  import { MinusCircleOutlined, PlusOutlined } from '@ant-design/icons-vue';
  import Button from '@sscd/button';
  import Input from '@sscd/input';
  import Space from '@sscd/space';
  import Form from '@sscd/form';
  import type { FormInstance } from '@sscd/form';
  interface User {
    first: string;
    last: string;
    id: number;
  }
  const formRef = ref<FormInstance>();
  const dynamicValidateForm = reactive<{ users: User[] }>({
    users: [],
  });
  const removeUser = (item: User) => {
    const index = dynamicValidateForm.users.indexOf(item);
    if (index !== -1) {
      dynamicValidateForm.users.splice(index, 1);
    }
  };
  const addUser = () => {
    dynamicValidateForm.users.push({
      first: '',
      last: '',
      id: Date.now(),
    });
  };
  const onFinish = (values) => {
    console.log('Received values of form:', values);
    console.log('dynamicValidateForm.users:', dynamicValidateForm.users);
  };
</script>
